package clas.ac.cn.common.utils;

import clas.ac.cn.common.exception.IException;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * @author zhangzhang
 * 获取basic请求头
 */
public class RequestUtil {

    public static String[] extractAndDecodeHeader(String header) throws IException {
        // Basic 截取 clientId:clientSecret
        if (header==null){
            throw new IException("解析请求头:"+header+"=>请求头为空!");
        }
        byte[] base64Token = header.trim().substring(6).getBytes(StandardCharsets.UTF_8);
        byte[] decoded;
        try {
            decoded = Base64.getDecoder().decode(base64Token);
        } catch (IllegalArgumentException var8) {
            throw new IException("请求头解析失败：" + header);
        }

        String token = new String(decoded, StandardCharsets.UTF_8);
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new IException("请求头无效：" + token);
        } else {
            return new String[]{token.substring(0, delim), token.substring(delim + 1)};
        }
    }
}
